package com.gosling.cloudspace.aop;

import com.alibaba.excel.annotation.ExcelProperty;
import com.gosling.cloudspace.common.annotation.DicZero;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.List;

/**
 * 去掉字符串的首尾空格
 *
 * @author lihonglin
 * @date 2023/4/23 15:01
 */
@Aspect
@Component
public class ZeroAspect {

    public static final Logger logger = LoggerFactory.getLogger(ZeroAspect.class);

    @Pointcut("@annotation(com.gosling.cloudspace.common.annotation.DicZero)")
    public void zero() {

    }

    @Before(value = "zero()")
    public void check4Offline(JoinPoint aspectJoinPoint) {
        Signature signature = aspectJoinPoint.getSignature();
        Class<?> clazz = signature.getClass();
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            try {
                //去除private权限，变为可更改
                field.setAccessible(true);
                DicZero annotation = field.getAnnotation(DicZero.class);
                ExcelProperty excelAnno = field.getAnnotation(ExcelProperty.class);
                String name = field.getName();
                PropertyDescriptor pd = new PropertyDescriptor(name, clazz);
                String value = (String) pd.getReadMethod().invoke(clazz);
                value = StringUtils.isNotBlank(value) ? value.trim() : null;
                //数据字典匹配
                List<String> dictionaryList = Arrays.asList(annotation.dictionary().split(","));
                if (StringUtils.isNotBlank(value) && !dictionaryList.contains(value)) {
                    if (DicZero.ADD_ZERO.equals(annotation.type())) {
                        field.set(name, DicZero.ZERO + value);
                    } else if (DicZero.REMOVE_ZERO.equals(annotation.type())) {
                        if (value.length() == 1) {
                            throw new Exception("[" + excelAnno.value()[0] + "]字段值非法");
                        } else {
                            field.set(name, value.substring(1));
                        }
                    }
                }
            } catch (IntrospectionException | IllegalAccessException | InvocationTargetException e) {
                logger.error("字段获取异常！");
                logger.error(e.getMessage(), e);
            } catch (Exception e) {
                logger.error("字段值非法！");
                logger.error(e.getMessage(), e);
            }
        }
    }

}
